package com.hxzy.framework.xss.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hxzy.framework.common.enums.WebFilterOrderEnum;
import com.hxzy.framework.web.config.SaasWebAutoConfiguration;
import com.hxzy.framework.xss.core.JsoupXssCleaner;
import com.hxzy.framework.xss.core.XssCleaner;
import com.hxzy.framework.xss.filter.XssFilter;
import com.hxzy.framework.xss.json.XssStringJsonDeserializer;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.util.PathMatcher;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.Filter;

/**
 * @Author wy
 * @Description xss自动装配置机制类 (springmvc配置)
 * @Date 2024/1/22 17:13
 * @Version 1.0
 */
@AutoConfigureAfter
@EnableConfigurationProperties(value = XssProperties.class)
@ConditionalOnProperty(prefix = "saas.xss",name="enable",havingValue = "true",matchIfMissing = true)
public class SassXssAutoConfiguration implements WebMvcConfigurer {

    /**
     * Xss 清理者
     * @ConditionalOnMissingBean  springboot 如果没有配置 XssCleaner  接口实现类，默认采用下面的下面的方式
     *
     * @return XssCleaner
     */
    @Bean
    @ConditionalOnMissingBean(XssCleaner.class)
    public XssCleaner xssCleaner() {
        return new JsoupXssCleaner();
    }

    /**
     * 注册 Jackson 的序列化器，用于处理 json 类型参数的 xss 过滤
     *
     * @return Jackson2ObjectMapperBuilderCustomizer
     */
    @Bean
    @ConditionalOnMissingBean(name = "xssJacksonCustomizer")
    @ConditionalOnBean(ObjectMapper.class)
    @ConditionalOnProperty(value = "saas.xss.enable", havingValue = "true")
    public Jackson2ObjectMapperBuilderCustomizer xssJacksonCustomizer(XssCleaner xssCleaner) {
        // 在反序列化时进行 xss 过滤，可以替换使用 XssStringJsonSerializer，在序列化时进行处理
        return builder -> builder.deserializerByType(String.class, new XssStringJsonDeserializer(xssCleaner));
    }


    /**
     * 创建 XssFilter Bean，解决 Xss 安全问题
     */
    @Bean
    @ConditionalOnBean(XssCleaner.class)
    public FilterRegistrationBean<XssFilter> xssFilter(XssProperties properties, PathMatcher pathMatcher, XssCleaner xssCleaner) {
        return SaasWebAutoConfiguration.createFilterBean(new XssFilter(properties, pathMatcher, xssCleaner), WebFilterOrderEnum.XSS_FILTER);
    }






}
